#include "thread_pool.h"

//线程池操作函数
void tp_init(threadpool_t * threadpool,int threadpoolsize){
    debug_log("tp_init");
    threadpool->threads = (pthread_t *)calloc(threadpoolsize,sizeof(pthread_t));
    threadpool->size = threadpoolsize;
    threadpool->queue = tq_init();
}
void tp_destroy(threadpool_t * threadpool){
    debug_log("tp_destroy");
    free(threadpool->threads);
    tq_destory(threadpool->queue);
}
void tp_start(threadpool_t * threadpool){
    debug_log("tp_start");
    for(int i = 0; i < threadpool->size; i++){
        int ret = pthread_create(&threadpool->threads[i],NULL,threadfunc,threadpool);
        debug_log("thread created.");
        if(0 != ret)
            error_log("tp_start::pthread_create");
    }
}
//线程执行函数
void * threadfunc(void * arg){
    debug_log("threadfunc");
    threadpool_t * threadpool = (threadpool_t *)arg;
    while(1){
        task_t * task;
        tq_dequeue(threadpool->queue,task);
        syslog(LOG_INFO,"tid(%ld) get fd:%d",pthread_self(),task->peerfd);
        if(task->peerfd > 0){
            //子线程处理任务
            thread_task(task);

            epoll_add_fd(task->peerfd);
            free(task->argument);
            free(task);
        }else{
            break;
        }
    }
    pthread_exit(0);
}
//子线程处理任务
void thread_task(task_t * task){
    debug_log("thread_task");
    task->funcname(task->argument);
}